#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file: access_token.py
@time: 2024-07-14 16:05
@desc: 
"""
import traceback
import requests
from global_scope import get_wechat_appid, get_wechat_secret, set_wechat_access_token
WechatGetAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token"


def wechat_access_token_request(logger):
    try:
        logger.info("Wechat Access Token Request Prepare")
        response = requests.get(WechatGetAccessTokenUrl, params={
            "grant_type": "client_credential",
            "appid": get_wechat_appid(),
            "secret": get_wechat_secret()
        })
        logger.info("Wechat Access Token Request Start")
        if 200 <= response.status_code < 300:
            logger.info(f"Wechat Access Token Request Success: {response.status_code}")
            resp = response.json()
            set_wechat_access_token(resp["access_token"])
        else:
            logger.info(f"Wechat Access Token Request Failed: {response.status_code}")
            logger.info(f"Wechat Access Token Request Failed: {response.content}")
    except Exception as e:
        logger.error(f"Wechat Access Token Request error: {e}")
        t = traceback.format_exc()
        logger.error(f"Wechat Access Token Request Error:{e}\n{t}")
    finally:
        logger.info("Wechat Access Token Request Finished")